package LeetCode.t2;

/**
 * @author: Laity
 * @Project: JavaLaity
 * @Package: LeetCode.t2.AddTwoNumbers
 * @Date: 2022年11月11日 14:26
 * @Description: Leetcode第2题：两数相加
 */
public class AddTwoNumbers {

    /**
     * 输入：l1 = [2,4,3], l2 = [5,6,4]
     * 输出：[7,0,8]
     * 解释：342 + 465 = 807
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        int carry = 0;
        // 其中一个不为null就往下走
        while (l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = (x + y + carry) % 10;
            carry = (x + y + carry) / 10;
            cur.next = new ListNode(sum);
            cur = cur.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            cur.next = new ListNode(1);
        }
        return dummyHead.next;
    }


    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        System.out.println(listNode.next);
    }

    /**
     * ListNode
     */
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
